package com.jdk.demo.nio.bytebuffer;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

public class ScatterAndGather {

	public static void main(String[] args) throws IOException {
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		InetSocketAddress address = new InetSocketAddress(8899);
		serverSocketChannel.socket().bind(address);

		int messageLength = 2 + 3 + 4;

		ByteBuffer[] buffers = new ByteBuffer[3];

		buffers[0] = ByteBuffer.allocate(2);
		buffers[1] = ByteBuffer.allocate(3);
		buffers[2] = ByteBuffer.allocate(4);

		SocketChannel socketChannel = serverSocketChannel.accept();

		while(true) {
			int bytesRead= 0;

			while(bytesRead < messageLength) {
				// 也可以接受一个buffer数组，这样可以一个buffer一个buffer的读入数据。可以用于自定义协议，比如协议头10个字节，协议体20个字节，我们就可以传入一个10字节和一个20字节的buffer数组
				long r = socketChannel.read(buffers);
				bytesRead += r;

				System.out.println("bytesread: " + bytesRead);

				Arrays.asList(buffers).stream().map(buffer -> "position: " + buffer.position() + ", limit: " + buffer.limit()).forEach(System.out::println);
			}

			Arrays.asList(buffers).forEach(buffer -> {
				buffer.flip();
			});

			long bytesWritten = 0;
			while(bytesWritten < messageLength) {
				long r = socketChannel.write(buffers);
				bytesWritten += r;
			}

			Arrays.asList(buffers).forEach(buffer -> {
				buffer.clear();
			});

			System.out.println("bytesRead: " + bytesRead + ", bytesWritten: " + bytesWritten + ", messageLength: " + messageLength);
		}
	}

}
